package com.github.tommas.decompiler;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class NoopDecompiler implements Decompiler {
    private final String root;
    public NoopDecompiler(String rootDir) {
        root = rootDir;
    }

    @Override
    public void decompile(String className, byte[] classfileBuffer) {
        int idx = className.lastIndexOf("/");
        String filename = "";
        String path = root;
        if (idx < 0) {
            filename = className + ".class";
        } else {
            filename = className.substring(idx + 1) + ".class";
            path += File.separator + className.substring(0, idx);
        }

        File dir = new File(path);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                throw new RuntimeException(String.format("Can not create directory %s", path));
            }
        }

        File file = new File(path + File.separator + filename);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(classfileBuffer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
